package com.yzt.zhuju.utils;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.main.MainTabEvent;
import com.yzt.p_base.utils.LogDataUtils;
import com.yzt.p_base.utils.StringUtils;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * author : bob
 * date   : 2022/11/30
 * desc   : 网络链接工具类
 */
public class UrlUtil {

    public static final String ROOT_PATH = "xysanchor://route:8080";

    /**
     * 邀请对方认证
     */
    public static final String TYPE_ROUTER_INVITE_AUTH = "LP://message/inviteIdentification";

    public static void parseTurnToPage(String url) {
        if (StringUtils.isEmpty(url) || "null".equals(url)) {
            return;
        }
        if (isRouterUrl(url)) {
            turnToARoutePage(url);
        } else {
            if (url.startsWith("https://") || url.startsWith("http://")) {
                RouterMain.goToWeb(url);
            }
        }
    }

    public static void turnToARoutePage(String url) {
        try {
            if (!isRouterUrl(url)) {
                return;
            }
            String urlpage = UrlPage(url).replace(ROOT_PATH, "").trim();
            Map<String, String> urlRequest = URLRequest(url);
            LogDataUtils.d("urlPage == " + urlpage);
            Postcard postcard = ARouter.getInstance().build(urlpage);
            Set<Map.Entry<String, String>> paramEntrys = urlRequest.entrySet();
            Iterator<Map.Entry<String, String>> iterator = paramEntrys.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> item = iterator.next();
                LogDataUtils.d("key == " + item.getKey() + ", value == " + item.getValue());
                if ("login".equals(item.getKey()) && "0".equals(item.getValue())) {
                    postcard.greenChannel();
                    continue;
                }
                if (item.getKey().endsWith("_int")) {
                    postcard.withInt(item.getKey().split("_")[0], NumberFomateUtils.coverToNumber(item.getValue()));
                } else if (item.getKey().endsWith("_boolean")) {
                    postcard.withBoolean(item.getKey().split("_")[0], "1".equals(item.getValue()));
                } else {
                    try {
                        String strValue = URLDecoder.decode(item.getValue(), "utf-8");
                        postcard.withString(item.getKey(), strValue);
                    } catch (Exception e) {
                        postcard.withString(item.getKey(), item.getValue());
                        e.printStackTrace();
                    }
                }
            }
            postcard.navigation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void turnToARoutePage4JO(String arouterJson) {
        if (TextUtils.isEmpty(arouterJson)) {
            return;
        }
        try {
            turnToARoutePage4JO(JSONObject.parseObject(arouterJson));
        } catch (Exception e) {
            Log.e("e", e.getMessage());
        }
    }

    /**
     * 根据json跳转到对应的页面，还添加的event事件的发送
     *
     * @param json "path" -> "/webs/AppWebViewActivity"  "params" -> {JSONObject@24676}  size = 1
     */
    public static void turnToARoutePage4JO(JSONObject json) {

        try {

            //跳转任意activity页面
            String path = json.getString("path");
            //跳转传递得参数
            String params = json.getString("params");
            //是否发送event事件
            String event = json.getString("event");

            if (!TextUtils.isEmpty(path)) {
                Postcard postcard = ARouter.getInstance().build(path);
                if (!TextUtils.isEmpty(params)) {
                    JSONObject parseObject = JSONObject.parseObject(params);
                    Iterator iterator = parseObject.keySet().iterator();
                    while (iterator.hasNext()) {
                        String key = (String) iterator.next();
                        Object value = parseObject.get(key);
                        if (value instanceof Integer) {
                            postcard.withInt(key, (Integer) value);
                        } else if (value instanceof Float) {
                            postcard.withFloat(key, (Float) value);
                        } else if (value instanceof Boolean) {
                            postcard.withBoolean(key, (Boolean) value);
                        } else if (value instanceof String) {
                            postcard.withString(key, (String) value);
                        }
                    }
                }
                postcard.navigation();
            }

            if (!TextUtils.isEmpty(event)) {
                if (!TextUtils.isEmpty(params)) {
                    JSONObject jsonObject = JSONObject.parseObject(params);
                    int matchType = jsonObject.getInteger("matchType");
                    RxBus.getDefault().post(new MainTabEvent(event, matchType));
                } else {
                    RxBus.getDefault().post(new MainTabEvent(event));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean isRouterUrl(String url) {
        Matcher matcher = Pattern.compile("xysanchor:\\/\\/route:8080\\/([a-z]+)(\\?*)?").matcher(url);
        return matcher.find();
    }

    /**
     * 解析出url请求的路径，包括页面
     *
     * @param strUrl url地址
     * @return url路径
     */
    public static String UrlPage(String strUrl) {
        String strPage = null;
        String[] arrSplit;

        strUrl = strUrl.trim();
        if (!strUrl.contains("?")) {
            return strUrl;
        }
        arrSplit = strUrl.split("[?]");
        if (strUrl.length() > 0) {
            if (arrSplit.length > 1) {
                if (arrSplit[0] != null) {
                    strPage = arrSplit[0];
                }
            }
        }
        return strPage;
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     *
     * @param strUrl url地址
     * @return url请求参数部分
     */
    private static String TruncateUrlPage(String strUrl) {
        String strAllParam = null;
        String[] arrSplit;

        strUrl = strUrl.trim();

        arrSplit = strUrl.split("[?]");
        if (strUrl.length() > 1) {
            if (arrSplit.length > 1) {
                if (arrSplit[1] != null) {
                    strAllParam = arrSplit[1];
                }
            }
        }

        return strAllParam;
    }

    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     *
     * @param URL url地址
     * @return url请求参数部分
     */
    public static Map<String, String> URLRequest(String URL) {
        Map<String, String> mapRequest = new HashMap<String, String>();

        String strUrlParam = TruncateUrlPage(URL);
        if (strUrlParam == null) {
            return mapRequest;
        }
        //每个键值为一组 www.2cto.com
        String[] arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }
}
